package com.atguigu.gmall.product.controller;

import com.atguigu.gmall.common.result.Result;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FilenameUtils;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient1;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RefreshScope
@RestController
@RequestMapping("/admin/product")
public class FlieUploadController {

    @Value("${imgUrl}")
    private String imgUrl;

    @ApiOperation(value = "图片上传")
    @PostMapping("/fileUpload")
    public Result fileUpload(MultipartFile file) throws Exception{
        String path2 = ClassUtils.getDefaultClassLoader().getResource("fdfs_client.conf").getPath();
        //初始化配置文件
        ClientGlobal.init(path2);
        //获取连接
        TrackerClient trackerClient = new TrackerClient();
        //获取存储节点的Ip及端口号
        TrackerServer trackerServer = trackerClient.getConnection();
        //连接存储节点
        StorageClient1 storageClient1 = new StorageClient1(trackerServer,null);
        //截取文件后缀名
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        //上传文件
        String path = storageClient1.upload_file1(
                file.getBytes(),
                extension,
                null
        );//文件位置，文件扩展名，文件描述信息
        System.out.println(imgUrl+path);
        return Result.ok(imgUrl+path);
    }
}
